<template>
  <view class="phxx-item-detail">
    <view class="content-box" v-show="!showReadMe">
      <view class="title-item">
        基本信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title">供应商</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.supplierName" />
        </view>
        <view class="uni-form-item" v-if="waybillData.waybillRespVO.planType == 1">
          <view class="title">装货地</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.loadingSiteName" />
        </view>
        <view class="uni-form-item" v-else>
          <view class="title">卸货地</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.loadingSiteName" />
        </view>
      </view>
      <view class="title-item">
        司机信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>车牌号</view>
          <input class="uni-input disab-box" disabled :value="selectedCar" placeholder="请选择车辆" @click="open" />
        </view>
        <view class="uni-form-item">
          <view class="title">司机姓名</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.carName" />
        </view>
        <view class="uni-form-item">
          <view class="title">身份证号</view>
          <view class="uni-input disab-box">{{driverCard}}</view>
        </view>
      </view>
      <view class="title-item">
        产品信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>产品</view>
          <view class="uni-select-box">
            <view class="uni-input" @click="showPop">{{selectedProd || ''}}</view>
            <uni-icons type="forward" size="20"></uni-icons>
          </view>
          <uv-picker ref="selectBoxPop" :confirmColor="curColor" :columns="productLists" keyName="text"
            @confirm="handleProd"></uv-picker>
        </view>

        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发皮重</view>
          <input class="uni-input" v-model="tareWeight" placeholder="请输入矿发皮重" @input="inputTareWeight" />
          吨
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发毛重</view>
          <input class="uni-input" v-model="grossWeight" placeholder="请输入矿发毛重" @input="inputGrossWeight" />
          吨
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发净重</view>
          <input class="uni-input" v-model="prodWeight" placeholder="请输入矿发净重" @input="inputWeight" />
          吨
        </view>

        <view class="uni-form-item">
          <view class="demonstration title"><span style="color:red;">*</span>磅单时间</view>
          <w-picker :visible="poundListFlag" mode="date" startYear="1900" endYear="2124" :value="curDateTime"
            :current="false" fields="second" @confirm="onConfirm($event,'date1')" @cancel="onCancel"
            :disabled-after="false" ref="date1"></w-picker>
          <input class="uni-input prd-mess disab-box" disabled v-model="datetimesingle" placeholder="请选择磅单打印时间"
            @click="poundListFlag=true"></input>
        </view>

        <view class="uni-form-item" style="height: 220rpx;justify-content: flex-start;">
          <view class="title"><span style="color:red;">*</span>磅单信息</view>
          <image class="cover-img band-img first-img" v-if="imagesPath.length > 0" :src="imagesPath[0]"
            @click="clickImg" mode="aspectFill"></image>
          <image class="cover-defaultImg band-img" @click="select" :src="imagesDefaultPath" mode="aspectFill"></image>
        </view>

      </view>
      <view class="btns">
        <button :class="{ 'loading': isLoading }" type="primary" @click="handleJieDan">
          确认接单
          <view v-if="isLoading" class="loading-icon"></view>
        </button>
      </view>
    </view>

    <!-- 车辆选择弹窗 -->
    <uni-popup class="carPop" ref="popup">
      <view class="carList">
        <view class="top">
          <view class="title">
            选择车牌
            <view class="cph" @click="handleAddCar">
              <image :src="backImgAdd"></image>
            </view>
          </view>
        </view>
        <view class="a-i-c">
          <view v-for="(item, index) in vehicleList" :key="index">
            <view class="item-box" :class="{'car-box': index == (vehicleList.length -1)} " @click="handleCar(item)">
              <view class="cph">
                <image :src="carImg"></image>{{ item.vehicleNo }}
              </view>
              <view class="status">
                <text class="isReal" v-if="item.isIdentified">已认证</text>
                <text class="isnotReal" @click="recognizeCar(item)" v-else>未认证</text>
              </view>
            </view>
          </view>

        </view>
      </view>
    </uni-popup>
    <!-- 阅读 -->
    <view v-if="showReadMe">
      <view class="back-meng"></view>
      <view class="phxx-itemss">
        <view class="header">
          <view class="title">《华业开泰运输管理协议》</view>
        </view>
        <view class="top">
          <view>司机考核要求，进入站台重车司机发生发现以下情形，视情况确认执行以下制度：</view>
          <view class="tit">
            1、进入集运站的大型运输车辆，车速不得超过 5 公里/小时。超速者扣除运费 50 元造成事故移交公安机关处理。
          </view>
          <view class="tit">
            2、进入集运站的大型运输车辆，按照华业开泰相关规定扫 码登记，未按照规定扫码，登记强行闯杆者给予扣除运费 100~300 元。
          </view>
          <view class="tit">
            3、大型运输车辆做好环保遮盖工作，在磅房前 20
            米指定区域揭开遮盖篷布后方可上磅，并积极配合工作人员查验煤质，不揭篷布、不配合查验煤质者，给予扣除运费100~500元;运输车辆环保工作不到位，致使运输货物抛洒路面，视其情节轻重给予扣除运费 100~200 元。
          </view>
          <view class="tit">
            4、严禁洒水，一经发现罚款3000元。
          </view>
        </view>
        <view class="btn">
          <view class="read">
            <view class="read-box" @click="handleChange">
              <image v-if="agree" :src="checkImg" style="width: 30rpx; height: 30rpx"></image>
              <image v-else :src="uncheckImg" style="width: 30rpx; height: 30rpx"></image>
            </view>
            我已阅读并同意
          </view>
          <button :class="{ 'not-read': !agree }" type="primary" @click="closeLinepop">
            同意
          </button>
        </view>
      </view>
    </view>
    <tip-box :show="showBlacklistTip" :message="blacklistTip" :duration="8000" @showTip="showTip"></tip-box>
  </view>
</template>
<script>
  import func from '@/utils/funlogin.js';
  import { setTenantId, getOpenId, getTenantId, getAccessToken, getWayBillNo, setWayBillNo, removeWayBillNo, setToken, setDriverId } from '@/utils/auth';
  import { getOpenIdByCode, getTenantsByOpenId, getPhoneByOpenid, wxPhoneLogin } from '@/api/login.js';
  import {
    getCustList, getLineUpByDriver, getDriving, checkRuningCar, getWayBillDetail, getLineUpDetail, getWayBillDetailLatest, getProductsLists, getTransPlanDetail,
    getVehicle, addWaybillLists, creatLineUp, getTenantConfig, updateViolation, addViolation, paymentReq, findLineupSwitchByTenant
  } from '@/api/me.js';
  import { toast, getCurrenDate, showConfirm } from '@/utils/common';
  import config from '@/config'

  export default {
    data() {
      return {
        lineupSwitch: 0,
        errorMsg: undefined,
        isJiedanRead: false,
        agree: false,
        isLoading: false,
        waybDialog: false,
        coalmineFlag: false,
        curDateTime: '',
        driverCard: '',
        curDateTime2: '',
        poundListFlag: false,
        switchText: "我的排号",
        isNeedLineup: true,
        planId: undefined,
        productLists: [],
        datetimesingle: undefined,
        datetimesingle2: undefined,
        prodWeight: undefined,
        grossWeight: undefined,
        tareWeight: undefined,
        currentPayStatus: false,
        waybillDialogFlag: false,
        waybillDialogDetailFlag: false,
        waybillFinishDialogFlag: false,
        refreshFlag: false,
        showCard: false,
        contractImg: config.baseImgUrl + '/contract-up.svg',
        contractupImg: config.baseImgUrl + '/contract.svg',
        currentStatus: false,
        loading: false,
        imagesDefaultPath: config.baseImgUrl + '/img.png',
        waybillStatusName: 0,
        isPdDistance: false,
        imagesPath: [],
        imagesPath2: [],
        isJieDan: false,
        imagesDefaultPath2: config.baseImgUrl + '/img.png',
        carListFlag: false,
        jTNum: 0,
        waybillStatusPay: false,
        hasLoadPage: false, // 上传照片 onshow
        vehicleList: [],
        selectedCar: '',
        selectedProd: undefined,
        ysjhData: '', // 从接单而来的参数
        currentWIndow: '',
        showBlacklistTip: false,
        blacklistTip: '',
        waybillData: {
          "waybillRespVO": {
            "planNo": "",
            "enterId": "",
            "openId": "",
            "supplierName": "",
            "waybillNo": "",
            "planType": 1,
            "planTypeName": "",
            "loadingSiteId": undefined,
            "loadingSiteName": "",
            "bizType": 0,
            "carBrand": "",
            "carCard": "",
            "driverId": "",
            "carName": "",
            "carPhone": "",
            "mineralTime": "",
            "mineralNetWeight": 0,
            "mineralTareWeight": 0,
            "mineralGrossWeight": 0,
            "proId": "",
            "supId": "",
            "userId": undefined,
            "uuid": ""
          },
          "hours": 0,
          "minutes": 0,
          "currentLineupCount": 0,
          "enableStatus": undefined,//状态
        },
        showReadMe: false,
        priceNum: 0,
        priceNumText: '排号',
        payRefundTime: 0,
        sjjdFormData: {},
        queryParam: {
          pageNo: 1,
          pageSize: 100
        },
        waybillNo: '',
        imageStyles: {
          width: 100,
          height: 100
        },
        cuttentType: '',
        payParam: {
          timeStamp: '',
          paySign: '',
          nonceStr: '',
          package: ''
        },
        custList: [],
        supId: undefined,
        curType: 2,
        rowNumberData: [],
        rowKey: ['customerName', 'waybillStatusName'],
        wayBillStatusList: [],
        queryParam: {
          pageNo: 1,
          pageSize: 3,
          vehicleNo: '',
          startTime: '',
          endTime: ''
        },
        pageParams: {
          isMore: 'more'
        }
      };
    },
    methods: {
      inputWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('请输入矿发净重')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('请输入合理吨位')
          this.prodWeight = undefined;
        } else {
          if (value < 0.01 || value > 100) {
            toast('请输入合理吨位,范围为0.01到100');
            this.prodWeight = undefined;
          }
        }
      },
      inputTareWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('请输入矿发皮重')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('请输入合理吨位')
          this.tareWeight = undefined;
        } else {
          if (value < 0.01 || value > 100) {
            toast('请输入合理吨位,范围为0.01到100');
            this.tareWeight = undefined;
          }
        }
      },
      inputGrossWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('请输入矿发毛重')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('请输入合理吨位')
          this.grossWeight = undefined;
        } else {
          if (value < 0.01 || value > 100) {
            toast('请输入合理吨位,范围为0.01到100');
            this.grossWeight = undefined;
          }
        }
      },
      handleChange() {
        this.agree = !this.agree
      },
      closeLinepop() {
        if (!this.agree) return
        this.showReadMe = false
      },
      onConfirm(res, type) {
        this.datetimesingle = res.result
        this.poundListFlag = false
      },
      showPop() {
        this.$refs['selectBoxPop'].open('bottom');
      },
      onCancel() {
        this.poundListFlag = false
      },

      getLinePay(price, time) {
        this.priceNum = parseFloat(price / 100).toFixed(2)
        this.priceNumText = `排号(${this.priceNum}元)`
        this.payRefundTime = time
      },
      cancelFirm() {
        this.$refs['payConfirmShow'].close();
      },
      clickImg() {
        let _this = this;
        _this.refreshFlag = true
        let imgsArray = [];
        uni.previewImage({
          urls: [this.imagesPath[0]]
        });
      },
      recognizeCar(item) {
        uni.setStorageSync('isSetSjxx', 'jl');
        this.$tab.reLaunch(`/packageB/pages/common/vehicle-editing/vehicle-editing?id=${item.id}`);
      },
      // 获取租户配置
      async gettenantConfig() {
        try {
          let res = await getTenantConfig();
          if (res.code == 0) {
            // this.waybillData.waybillRespVO.waybillSource = res.data.waybillSrc;
          }
        } catch (e) {
          return false;
        }
      },

      //接单生成运单
      async handleJieDan() {
        if (this.isLoading) return
        console.log('接单啦')
        this.waybillData.waybillRespVO.carBrand = this.selectedCar
        //校验参数
        if (!this.waybillData.waybillRespVO.carBrand) {
          toast(`请选择车辆`);
          return
        }
        if (!this.datetimesingle) {
          toast(`磅单时间必须为年-月-日 时-分-秒`);
          return
        }
        if (!this.tareWeight) {
          toast(`请输入合理吨位的矿发皮重`);
          return
        }
        if (!this.grossWeight) {
          toast(`请输入合理吨位的矿发毛重`);
          return
        }
        if (!this.prodWeight) {
          toast(`请输入合理吨位的矿发净重`);
          return
        }
        const calculatedNetWeight = (Number(this.grossWeight) - Number(this.tareWeight)).toFixed(2);
        const inputProdWeight = Number(this.prodWeight).toFixed(2);
        if (Number(calculatedNetWeight) !== Number(inputProdWeight)) {
          showConfirm(`矿发数据有误,请重新输入`)
          return
        }
        if (!this.waybillData.waybillRespVO?.uuid && !this.imagesPath[0] &&
          this.waybillData.waybillRespVO?.planType == 1) {
          toast(`请上传磅单照片`);
          return
        }
        this.isLoading = true
        this.waybillData.waybillRespVO.uuid = this.imagesPath[0]
        this.waybillData.waybillRespVO.customerName = undefined
        this.waybillData.waybillRespVO.containerNo = undefined
        this.waybillData.waybillRespVO.supId = uni.getStorageSync('supIdFlag')
        this.waybillData.waybillRespVO.mineralNetWeight = Number(this.prodWeight)
        this.waybillData.waybillRespVO.mineralTareWeight = Number(this.tareWeight)
        this.waybillData.waybillRespVO.mineralGrossWeight = Number(this.grossWeight)
        this.waybillData.waybillRespVO.mineralTime = this.datetimesingle
        this.waybillData.waybillRespVO.waybillNo = undefined
        this.waybillData.waybillRespVO.userId = uni.getStorageSync('curUserId')
        this.waybillData.waybillRespVO.enterId = getTenantId()
        let code1 = await func.wxLogin();
        let openid = await getOpenIdByCode(code1);
        console.log(openid.data, '这是获取的openid================')
        this.waybillData.waybillRespVO.openId = openid.data
        this.waybillData.waybillRespVO.planNo = this.planId
        this.waybillData.waybillRespVO.planTypeName = this.waybillData.waybillRespVO.planType == 1 ? "采购计划" : "销售计划"
        try {
          console.log(this.waybillData.waybillRespVO, 'waybillRespVO============')
          let res = await addWaybillLists(this.waybillData.waybillRespVO);
          if (res.code == '200') {
            uni.removeStorageSync('supIdFlag')
            this.waybillDialogFlag = false
            setWayBillNo(this.waybillData.waybillRespVO.waybillNo)
            this.linkToPage()
          } else if (res.code === '12000') {
            this.blacklistTip = res.msg
            this.showBlacklistTip = true
          } else {
            toast(`${res.msg}`)
          }
        } catch (e) {
          return false;
        }
        this.isLoading = false
      },
      linkToPage() {
        if (this.lineupSwitch === 0) {
          uni.setStorageSync('orderType', 1);
          this.$tab.reLaunch(`/pages/index?carno=${this.selectedCar}`)
          return;
        }
        if (this.waybillData.waybillRespVO.planType == 1) {
          this.$tab.reLaunch('/pages/waybill?type=deliver')
        } else {
          this.$tab.reLaunch('/pages/waybill?type=deliver')
        }
      },
      async findLineupSwitchByTenant() {
        const res = await findLineupSwitchByTenant(getTenantId())
        if (res.code === '200') {
          this.lineupSwitch = res.data?.lineupSwitch
        }
      },
      handleAddCar() {
        uni.setStorageSync('isSetSjxx', 'jl');
        uni.navigateTo({
          url: '/packageB/pages/common/vehicle-editing/vehicle-authentica?type=code'
        });
      },
      handleProd(e) {
        if (this.productLists.length > 0) {
          this.selectedProd = e.value[0].text
          this.waybillData.waybillRespVO.proId = e.value[0].value
        }
      },
      async handleCar(item) {
        console.log(getOpenId(), 'handleCar')
        //先去校验该车辆是否有正在执行中的运单
        let res = await checkRuningCar({
          "vehicleNo": item.vehicleNo,
          "enterId": getTenantId()
        })
        if (res.code != '200') {
          toast(`${res.msg}`)
          return
        }
        this.selectedCar = item.vehicleNo;
        this.waybillData.waybillRespVO.carBrand = item.vehicleNo;
        this.checkCarAndImagNull()
        uni.setStorageSync('vehicleNoByCode', item.vehicleNo);
        this.$refs['popup'].close();
      },
      checkCarAndImagNull() {
        this.loading = this.waybillData.waybillRespVO?.planType == 1 ?
          (!!this.waybillData.waybillRespVO.carBrand ? true : false) :
          ((!!this.waybillData.waybillRespVO.carBrand && !!this.waybillData.waybillRespVO.uuid) ? true : false)
      },
      change(e) {
        console.log('e:', e);
      },
      open() {
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        this.$refs['popup'].open('bottom');
      },
      openProdct() {
        this.$refs['prodPopup'].open('bottom');
      },
      // 获取司机最新运单详情
      async getLatestWayBill(type) {
        try {
          let res = await getWayBillDetailLatest({
            "tenant-id": getTenantId(),
            "Authorization": 'Bearer ' + getAccessToken(),
          }, { businessType: 1 });
          if (res.code == 0) {
            if (!!res.data) {
              //有数据则判断运单状态
              console.log('司机有最新运单那么去判断他的状态========================')
              let status = res.data.waybillStatus
              if (status == 9 || status == 8 || status == 7) {
                if (type == 'code') {
                  this.isJiedanRead = true
                  this.getTransPlanData(uni.getStorageSync('ysjhData').planId)
                }
              } else {
                if (this.lineupSwitch === 0) {
                  this.getWayBillDetails(res.data.waybillNo, type);
                } else {
                  this.getTransPlanData(uni.getStorageSync('ysjhData').planId)
                }
              }
            } else {
              //无数据
              if (type == 'code') {
                console.log('司机是扫码过来的且无数据直接接单========================')
                this.isJiedanRead = true
                this.getTransPlanData(uni.getStorageSync('ysjhData').planId)
              } else {
                console.log('司机最新没运单不是扫码过来的提示用户========================')
                toast(`您暂时没有运单，请先接单！`);
                this.waybillDialogFlag = false
              }
            }
          } else {
            toast(res.msg);
          }
        } catch (e) {
          return false;
        }
      },
      //获取车辆列表
      async getCarList() {
        try {
          //遍历对象过滤空值
          let data = {
            pageNo: 1,
            pageSize: 100,
          };
          console.log('getVehicle===: ');
          let res = await getVehicle(data);
          if (res.code == 0) {
            console.log('getVehicle: ', res);
            this.vehicleList = res.data.list;
          }
        } catch (e) {
          return false;
        }
      },

      //选择上传触发函数
      select(e) {

        console.log('触发了上传select')
        let that = this
        that.isJieDan = true
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album'], //从相册选择
          success: function (res) {
            wx.showLoading({
              title: '正在上传...',
            });
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }
            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                that.uploadFiles(resp.tempFilePath);
              },
              fail: (error) => {
              },
            })
          }
        });
      },

      uploadFiles(filepath) {
        let _ = this
        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload',
          filePath: filepath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': 'Bearer ' + getAccessToken(),
          },
          success(res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              console.log(JSON.parse(res.data));
              _.waybillData.waybillRespVO.uuid = JSON.parse(res.data).data;
              _.imagesPath = [];
              _.imagesPath.push(JSON.parse(res.data).data);
              uni.setStorageSync('loadingWeighbridgeByCode', JSON.parse(res.data).data);
              _.currentWIndow = 1
              _.waybillDialogFlag = true
            } else {
              if (res.statusCode === 413) {
                toast('上传图片过大，请重新上传，不要选择原图')
              } else {
                toast('上传失败，状态码:', res.statusCode)
              }
            }
          },
          fail(err) {
            wx.hideLoading();
            uni.showToast({
              title: '上传失败'
            });
            _.checkCarAndImagNull()
            _.currentWIndow = 1
            _.waybillDialogFlag = true
          }
        })
      },
      // 移出图片函数
      async deletephoto() {
        console.log('shanchu');
      },
      async getWayBillDetails(id, type) {
        try {
          let res = await getLineUpDetail({
            waybillNo: id,
            businessType: 1
          });
          if (res.code == 0) {
            let isFromCode = true // 从接单过来且状态是已入场之后，展示已完成的详情
            let lineupSwitch = res.data.lineupSwitch
            this.isNeedLineup = res.data.lineupSwitch == 1 ? false : true
            let waybillStatus = res.data.lineupVO.queueStatus
            let currentFlag = false
            this.waybillStatusPay = false
            this.waybillNo = res.data.lineupVO.waybillNo;
            //如果不需要排队，则只展示详情
            if (waybillStatus == 10010 || waybillStatus == 40020) {
              console.log('1.已预约/已取消排队========================')
              this.waybillStatusName = 1
              // uni.setStorageSync('firstSHowPop','')
            } else if (waybillStatus == 40010) {
              console.log('2.已排队========================')
              this.waybillStatusName = 0
              // uni.setStorageSync('firstSHowPop','')
            } else if (waybillStatus == 30010) {
              //排队未支付
              this.waybillStatusName = 1
              this.priceNumText = '排号10元'
              this.waybillStatusPay = true
            } else {
              console.log('3.除已预约取消排队，已排队外的其余========================')
              if (waybillStatus == 90000 || waybillStatus == 60040 || waybillStatus == 40050) {
                currentFlag = true
              }
              if (waybillStatus == 40050) {
                isFromCode = false
              }
              this.waybillStatusName = 0
              this.carListFlag = true
            }
            this.resetWaybillData()
            if ((this.waybillStatusName == 0) && (type == 'code') && currentFlag && isFromCode) {
              console.log('展示接单页面')
              this.carListFlag = false
              this.isJiedanRead = true
              this.getTransPlanData(uni.getStorageSync('ysjhData').planId)
            } else {
              uni.setStorageSync('orderType', 1);
              this.$tab.reLaunch(`/pages/index?codes=true&id=${id}`)
            }
          } else {
            toast(`${res.msg}`);
            //关闭所有弹窗，并不能展开
            this.errorMsg = res.msg
          }
        } catch (e) {
          return false;
        }
      },
      resetWaybillData() {
        this.waybillData = {
          "waybillRespVO": {
            "planNo": "",
            "enterId": "",
            "openId": "",
            "supplierName": "",
            "waybillNo": "",
            "planType": 1,
            "planTypeName": "",
            "loadingSiteId": undefined,
            "loadingSiteName": "",
            "bizType": 0,
            "carBrand": "",
            "carCard": "",
            "driverId": "",
            "carName": "",
            "carPhone": "",
            "mineralTime": "",
            "mineralNetWeight": 0,
            "mineralTareWeight": 0,
            "mineralGrossWeight": 0,
            "proId": "",
            "supId": "",
            "userId": undefined,
            "uuid": ""
          },
          "hours": 0,
          "minutes": 0,
          "currentLineupCount": 0,
          "enableStatus": undefined,//状态
        }
      },
      async getTransPlanData(id) {
        uni.setNavigationBarTitle({
          title: '接单'
        });
        let _ = this
        _.curType = 2
        _.getCarList();
        uni.removeStorageSync('vehicleNoByCode');
        uni.removeStorageSync('loadingWeighbridgeByCode');
        _.resetWaybillData()
        try {
          let res = await getTransPlanDetail({
            planNo: id,
            isOperation: uni.getStorageSync('ysjhData').isOperation
          });
          _.currentStatus = true
          if (res.code == "200") {
            let dateRes = getCurrenDate()
            _.curDateTime = dateRes.curYear + '-' + (dateRes.curMonth < 10 ? '0' + dateRes.curMonth : dateRes.curMonth) + '-' + (dateRes.curDay < 10 ? '0' + dateRes.curDay : dateRes.curDay) + ' ' + dateRes.curHour + ':' + dateRes.curMinute + ':' + dateRes.curSecond
            console.log('运输计划详情=============??===============');
            console.log(res.data);
            uni.removeStorageSync('currentLinePageData');
            uni.setStorageSync('currentLinePageData', res.data);
            uni.setStorageSync('curUserId', res.data.userId);
            let driverInfo = uni.getStorageSync('sjxxData');
            console.log('driver=============??===============');
            console.log(driverInfo);
            _.carListFlag = false
            _.waybillDialogFlag = true
            _.waybillData.waybillRespVO.supplierName = res.data.supName
            _.waybillData.waybillRespVO.loadingSiteId = res.data.loadingSiteId
            _.waybillData.waybillRespVO.loadingSiteName = res.data.loadingSiteName
            // this.waybillData.waybillRespVO.coalSubtype = res.data.coalSubtype
            _.waybillData.waybillRespVO.planType = res.data.planType
            // _.waybillData.waybillRespVO.planNo = res.data.planNo
            _.waybillData.waybillRespVO.carName = driverInfo.driverName
            _.waybillData.waybillRespVO.carCard = driverInfo.idNo
            _.waybillData.waybillRespVO.driverId = driverInfo.id
            _.waybillData.waybillRespVO.carPhone = driverInfo.mobile
            _.driverCard = driverInfo.idNo.slice(0, 3) + '****' + driverInfo.idNo.slice(-3)
            _.currentWIndow = 1
            uni.setStorageSync('supIdFlag', res.data.supId)
            _.getProductsList(res.data.supId)
            if (_.isJiedanRead && res.data.purchaserId == 6) {
              _.showReadMe = true
            }
          } else {
            toast(res.msg)
          }
        } catch (e) {
          return false;
        }
      },
      async getProductsList(supId) {
        let res = await getProductsLists(supId)
        this.productLists =
          [res.data.map(item => {
            return {
              value: item.proId,
              text: item.proName
            }
          })]
      },
      showPageFromStorage(type) {
        let _ = this
        _.gettenantConfig();
        _.currentStatus = true
        let data = uni.getStorageSync('currentLinePageData');
        _.waybillData.waybillRespVO.supplierName = res.data.supName
        console.log('直接从缓存拿接单详情数据============================', data);
        _.getCarList()//再次获取车辆
        _.getProductsList(uni.getStorageSync('supIdFlag'))//再次获取产品
        _.carListFlag = false
        let driverInfo = uni.getStorageSync('sjxxData');
        _.waybillData.waybillRespVO.carName = driverInfo.driverName
        _.waybillData.waybillRespVO.carCard = driverInfo.idNo
        _.waybillData.waybillRespVO.driverId = driverInfo.id

        _.waybillData.waybillRespVO.carPhone = driverInfo.mobile
        // this.waybillData.waybillRespVO.planTypeName = data.planTypeName;
        // this.waybillData.waybillRespVO.customerId = data.customerId;
        _.waybillData.waybillRespVO.customerName = data.supplierName;
        _.waybillData.waybillRespVO.loadingSiteId = data.loadingSiteId;
        _.waybillData.waybillRespVO.loadingSiteName = data.loadingSiteName;
        // this.waybillData.waybillRespVO.coalSubtypeName = data.coalSubtypeName;
        // this.waybillData.waybillRespVO.coalSubtype = data.coalSubtype;
        _.waybillData.waybillRespVO.planType = data.planType;
        // this.waybillData.waybillRespVO.planNo = data.planNo; 
        // this.waybillData.waybillRespVO.shippersId = data.shippersId
        // this.waybillData.waybillRespVO.shippersName = data.shippersName
        _.selectedCar = uni.getStorageSync('vehicleNoByCode');
        _.waybillData.waybillRespVO.uuid = uni.getStorageSync('loadingWeighbridgeByCode');
        _.waybillData.waybillRespVO.carBrand = uni.getStorageSync('vehicleNoByCode');
        !!uni.getStorageSync('loadingWeighbridgeByCode') && (this.imagesPath.push(uni.getStorageSync('loadingWeighbridgeByCode')))
        _.checkCarAndImagNull()
        _.currentWIndow = 1
        _.waybillDialogFlag = true
      },

      // 获取登录状态
      async getLoginStatus() {
        console.log('判断登录状态是获取atoken', getAccessToken());
        // let code = await func.wxLogin();
        // console.log(code,'code================')
        if (getAccessToken()) {
          //已经登录
          this.rowNumberData = []
          this.getCustList();
          this.getRowList();
        } else {
          //没登陆 获取租户列表看是否以前注册过
          this.loginNew()
        }
      },
      //用户无感知登录
      async loginNew() {
        //获取wx code
        let code1 = await func.wxLogin();
        console.log(code1, '这是第一次获取的code================')
        let openid = await getOpenIdByCode(code1);
        console.log(openid.data, '这是第一次获取的openid================')
        this.getTenantids(openid.data)
      },
      async login(num) {
        //获取wx code
        let code = await func.wxLogin();
        let data = {
          phoneCode: num,
          loginCode: code
        };

        wxPhoneLogin(data).then((res) => {
          if (res.code == 0) {
            setToken({
              'accessToken': res.data.accessToken,
              'refreshToken': res.data.refreshToken,
            })
            setDriverId(res.data.userId)
            this.curType = 1
            this.switchText = "我的排号"
            this.getLoginStatus();
          }
        });
      },
      //获取司机租户信息
      async getTenantids(openid) {
        //获取wx code
        this.openid = openid
        let res1 = await getTenantsByOpenId(openid);
        if (res1.code == 0) {
          if (res1.data.length == 0) {
            this.$tab.reLaunch('/pages/login?type=code');
            return
          }
          this.tenantList = res1.data;
          if (res1.data.length == 1) {
            //直接用
            setTenantId(res1.data[0].id)
            let number = await getPhoneByOpenid(openid);
            console.log(number, '这是租户为一个的时候获取回来的手机号================')
            this.login(number.data);
          } else {
            console.log('这是获取到了多个租户列表==========:', res1.data);
            //跳转到租户下拉选择页面
            // this.$refs['tenantsDialog'].open('bottom');
            this.$tab.reLaunch(`/packageA/pages/tenant?openid=${openid}`);
          }
        }
      },

      //获取排号信息列表
      async getRowList() {
        try {
          //遍历对象过滤空值
          let data = {};
          Object.keys(this.queryParam).forEach((item) => {
            if (this.queryParam[item]) {
              data[item] = this.queryParam[item];
            }
          });
          this.pageParams.isMore = 'loading';
          let res = await getLineUpByDriver(data);
          if (res.code == 0) {
            if (this.queryParam.pageNo == 1) {
              this.rowNumberData = res.data.list;
            } else {
              this.rowNumberData = [...this.rowNumberData, ...res.data.list];
            }

            console.log('rowNumberData: ', this.rowNumberData);

            if (res.data.total == this.rowNumberData.length) {
              this.pageParams.isMore = 'noMore';
            } else {
              this.pageParams.isMore = 'more';
            }
          }
          //停止下拉刷新
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        } catch (e) {
          return false;
        }
      },
      //获取精简客户列表
      async getCustList() {
        //暂时去掉
        // try {
        // 	let res = await getCustList();
        // 	if (res.code == 0) {
        // 		this.custList = res.data;
        // 	}
        // 	console.log('getCustList: ', this.custList);
        // } catch (e) {
        // 	return false;
        // }
      },
      showTip(event) {
        this.showBlacklistTip = event
      }
    },
    async onLoad(options) {
      console.log('receiving页面进入onLoad=====================', options)
      await this.findLineupSwitchByTenant()
      this.planId = uni.getStorageSync('ysjhData').planId
      if (!!options) {
        this.curType = 2
        if (!!options.codes) {
          //是从接单过来的 
          let datas = uni.getStorageSync('ysjhData')
          this.gettenantConfig();
          if (!!datas?.planId) {//获取到缓存数据
            this.getLatestWayBill('code')
          }
          return
        } else {
          if (uni.getStorageSync('isSetSjxx')) {
            this.showPageFromStorage(2)
            uni.removeStorageSync('isSetSjxx');
          } else {
            if (JSON.stringify(options) == "{}") {
              this.curType = 1
              this.getLoginStatus()
              return
            }
          }
          uni.setNavigationBarTitle({
            title: '接单'
          });
        }
      }
    },
    computed: {
      checkImg() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/checked1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/checked.png';
        } else {
          return config.baseImgUrl + '/checked.png';
        }
      },
      uncheckImg() {
        return config.baseImgUrl + '/unchecked.png';
      },
      curColor() {
        return this.$store.state.user.curTypeColor
      },
      backImgAdd() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/add1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/add.png'
        } else { }
      },
      carImg() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/car1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/car.png'
        } else {
          return config.baseImgUrl + '/car.png'
        }
      },
    },
    onShow() {
      console.log('receiving页面进入onShow')
    },
    onHide() {
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep.carPop,
  .cardPop {
    background-color: #fff;
    width: 750rpx;
    height: 522rpx;

    .carList {
      border-radius: 10rpx;
      padding: 10rpx;
      background-color: #fff;
      width: 750rpx;
      height: 522rpx;
      overflow: auto;
      font-size: 14px;

      .top {
        padding: 14rpx 16rpx;
        height: 56px;
        line-height: 63rpx;
        font-size: 15px;
        color: #000;
        font-weight: bold;
        border-bottom: 1px solid #e6e6e6;
        background: #fff;
        width: 98%;
        marin: 0;
        text-align: center;
      }

      .add-box {
        position: fixed;
        bottom: 59rpx;
        background: #fff;
        display: flex;
        justify-content: space-between;
        width: 97%;
        height: 102rpx;
        line-height: 73rpx;
        padding: 20rpx;

        .cph:last-child {
          float: right;
        }

        .cph:first-child {
          text-indent: 10rpx;

          image {
            width: 60rpx;
            height: 60rpx;
            float: left;
          }
        }
      }

      .a-i-c {
        position: relative;
        max-height: 398rpx;
        overflow: scroll;

        .car-box {
          margin-bottom: 102rpx;
        }

        .item-box {
          height: 60rpx;
          line-height: 60rpx;
          box-sizing: content-box;
          padding: 20rpx;
          font-size: 15px;
          border-bottom: 1px solid #ccc;
          display: flex;
          justify-content: space-between;

          .cph {
            font-weight: bold;
            text-indent: 10rpx;

            image {
              width: 60rpx;
              height: 60rpx;
              float: left;
            }
          }

          .isReal {
            color: #fff;
            padding: 10rpx;
            background-color: #19be6b;
            border-radius: 6rpx;
            line-height: 50rpx;
          }

          .isnotReal {
            color: #fff;
            padding: 10rpx;
            background-color: #f56c6c;
            border-radius: 6rpx;
            line-height: 50rpx;
          }

          .goReal {
            color: #fff;
            margin-left: 40rpx;
            padding: 10rpx;
            background-color: #1890FF;
            border-radius: 6rpx;
            line-height: 50rpx;
          }
        }

      }
    }
  }

  .loading {
    position: relative;
  }

  .loading-icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 4px solid rgba(0, 0, 0, .1);
    border-left-color: transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 29%;
    left: 36%;
    transform: translate(-50%, -50%);
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .back-meng {
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    z-index: 8;
    left: 0;
    width: 100%;
    height: 100%;
  }

  .phxx-itemss {
    box-sizing: border-box;
    background: #fff;
    border-radius: 30rpx;
    width: 90vw;
    position: absolute;
    top: 12%;
    z-index: 9;
    left: 5vw;

    .header {
      width: 100%;
      height: 96rpx;
      line-height: 96rpx;
      border-bottom: 2rpx solid #EAEAEA;
      text-align: center;
      color: #000;
      font-size: 16px;
      font-weight: 600;
    }

    .top {
      padding: 30rpx;
      font-size: 15px;

      .tit {
        margin-bottom: 20rpx;
      }
    }

    .btn {
      padding: 11rpx;

      button.not-read {
        background: #ccc !important;
        ;
      }
    }

  }
</style>